package com.zhenyi.tuangou.index;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.utils.DateUtils;
import com.zhenyi.common.model.TgAddress;
import com.zhenyi.common.model.TgGroup;
import com.zhenyi.common.model.TgGroupProduct;
import com.zhenyi.common.model.TgOrder;
import com.zhenyi.common.model.TgProduct;
import com.zhenyi.common.model.TgUser;
import com.zhenyi.common.model.TgUserProductOrder;
import com.zhenyi.tuangou.core.OrderUtils;
import com.zhenyi.tuangou.core.WXPayUtils;
import com.zhenyi.tuangou.interceptor.WXInterceptor;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONObject;

public class OrderController extends TGController {

	/**
	 * 确认订单
	 */
	public void confirmOrder() {

		Integer productId = getParaToInt("id");// 商品ID
		if (productId == null) {
			renderFailure();
			renderError(500);
			return;
		}
		TgUser user = getUser();// 获取当前用户
		TgAddress address = user.getDefaultAddress();// 用户默认地址
		TgProduct product = TgProduct.dao.findById(productId);// 购买商品信息
		setAttr("product", product);// 购买商品信息
		// setAttr("type", type);
		setAttr("address", address);// 默认地址
		render("/buy.html");
	}

	/**
	 * 如果未提交第三方下单,则向第三方下单
	 */
	public void pushOrder() {
		String body = HttpKit.readData(getRequest());
		System.out.println(body);
		JSONObject jsonObject = new JSONObject(body);
		String orderCode = getPara("code");
		if (StrKit.isBlank(orderCode)) {
			renderError(404);
			return;
		}
		Long orderId = hashids.decode(orderCode)[0];
		TgOrder order = TgOrder.dao.findById(orderId);
		String address = jsonObject.getStr("address");
		String contact = jsonObject.getStr("contact");
		order.setAddress(address);
		order.setContact(contact);
		order.update();

		WXPayUtils payUtils = new WXPayUtils();
		String openId = order.getOpenId();
		String outTradeNo = order.getOutTradeNo();
		String total = String.valueOf(order.getTotalFee());
		Ret ret = payUtils.pushOrder(outTradeNo, total, IpKit.getRealIpV2(getRequest()), openId);
		if (ret.isFail()) {
			renderFailure();
			return;
		}
		@SuppressWarnings("unchecked")
		Map<String, String> packageParams = (Map<String, String>) ret.get("packageParams");
		renderSuccess(packageParams);
	}

	/**
	 * 点击购买下单下单
	 */
	@Before(WXInterceptor.class)
	public void addOrder() {
		Integer num = getParaToInt("num", 1);// 购买数量
		Long groupProductId = getParaToLong("id");// 几人团的ID
		Long groupId = getParaToLong("groupId");// 正在参团的团购ID

		ArrayList<Long> productIds = new ArrayList<>();
		TgUser user = getUser();

		TgOrder order = new TgOrder();
		order.setOpenId(user.getOpenId());

		String orderCode = getPara("code");
		if (StrKit.notBlank(orderCode)) {
			Long orderId = hashids.decode(orderCode)[0];
			order = TgOrder.dao.findById(orderId);
			String extra = order.getExtra();
			if (extra.contains(OrderUtils.GROUP)) {
				groupId = Long.parseLong(extra.replace(OrderUtils.GROUP, ""));
				TgGroup group = TgGroup.dao.findById(groupId);
				TgGroupProduct groupProduct = TgGroupProduct.dao.findById(group.getGroupProductId());
				productIds.add(groupProduct.getProductId());
			} else if (extra.contains(OrderUtils.GROUP_PRODUCT)) {
				groupProductId = Long.parseLong(extra.replace(OrderUtils.GROUP_PRODUCT, ""));
				TgGroupProduct groupProduct = TgGroupProduct.dao.findById(groupProductId);
				productIds.add(groupProduct.getProductId());
			} else if (extra.contains(OrderUtils.SETTLEMENT)) {
				String[] ids = extra.replace(OrderUtils.SETTLEMENT, "").split(";");
				for (int i = 0; i < ids.length; i++) {
					productIds.add(Long.parseLong(ids[i]));
				}
			} else {
				renderError(404);
				return;
			}
		} else if (groupProductId != null) {
			Ret ret = isExistOpenOrder(groupProductId);// 判断是否需要重新下单
			TgGroupProduct groupProduct = TgGroupProduct.dao.findById(groupProductId);

			if (ret.isOk()) {
				Long orderId = ret.getLong("orderId");
				order = TgOrder.dao.findById(orderId);
			} else {
				order = addOpenGroupOrder(num, groupProductId);// 订单信息
			}
			productIds.add(groupProduct.getProductId());
		} else if (groupId != null) {
			boolean canJoin = canJoin(groupId);
			if (!canJoin) {
				renderError(401);
				return;
			}
			Ret ret = isExistJoinOrder(groupId);// 判断是否需要重新下单
			if (ret.isOk()) {
				Long orderId = ret.getLong("orderId");
				order = TgOrder.dao.findById(orderId);
			} else {
				order = addJoinGroupOrder(num, groupId);// 订单信息
			}
			TgGroup group = TgGroup.dao.findById(groupId);
			TgGroupProduct groupProduct = TgGroupProduct.dao.findById(group.getGroupProductId());
			productIds.add(groupProduct.getProductId());

		} else {
			renderFailure();
			renderError(500);
			return;
		}

		setAttr("order", order);
		setAttr("orderCode", hashids.encode(order.getId()));

		List<TgProduct> products = new ArrayList<TgProduct>();
		for (Long productId : productIds) {
			TgProduct product = TgProduct.dao.findById(productId);// 购买商品信息
			products.add(product);
		}
		setAttr("products", products);

		if (!order.getUserId().equals(user.getId())) {
			renderError(401);
			return;
		}
		setAttr("address", user.getDefaultAddress());
		List<Record> list = getAddressList();// 选择地址
		setAttr("addressList", list);

		render("/res/orderConfirm.html");
	}

	/**
	 * 查询订单状态,是否已支付等
	 * 
	 * @param order
	 * @return
	 */
	private Ret queryOrderInfo(TgOrder order) {
		if (order.getStatus().equals(TgOrder.STATUS_SUCCESS)) {
			return Ret.ok();
		}
		return Ret.fail();
	}

	private OrderUtils orderUtils = new OrderUtils();

	public void payResult() {
		String address = getPara("address");// 收货地址
		String code = getPara("code");
		if (StrKit.isBlank(address) || StrKit.isBlank(code)) {
			renderError(404);
			return;
		}
		Long orderId = hashids.decode(code)[0];
		TgOrder order = TgOrder.dao.findById(orderId);
		order.setAddress(address);// 写入地址
		order.update();
		TgUser user = getUser();
		if (!user.getId().equals(order.getUserId())) {
			renderError(401);
			return;
		}
		int[] interval = { 1, 3, 5, 10 };
		for (int i : interval) {
			order = orderUtils.queryOrder(order);
			if (order.getStatus().equals(1)) {
				break;
			}
			ThreadUtil.safeSleep(i * 1000);
		}
		if (!order.getStatus().equals(1)) {
			renderError(404);
			return;
		}
		Kv cond = Kv.by("orderId", orderId);
		SqlPara sql1 = Db.getSqlPara("findGroupByOrderId", cond);
		Long groupId = Db.find(sql1).get(0).getLong("groupId");

		if (!order.getUserId().equals(user.getId())) {
			renderError(401);
			return;
		}

		setAttr("user", user);
		setAttr("order", order);
		Ret ret = queryOrderInfo(order);
		setAttr("orderStatus", ret.isOk());
		setAttr("shareCode", hashids.encode(groupId));
		DBMap map = new DBMap();
		map.put("orderId", orderId);
		map.put("userId", user.getId());
		TgProduct product = TgProduct.dao.searchFirst(map);
		setAttr("product", product);
		render("/res/groupBuyingResult.html");
		// redirect("/wechat/test?id=" + orderId);
	}

	/**
	 * 我的订单
	 */
	public void getOrder() {
		Integer status = getParaToInt("status");
		Long userId = getUser().getId();
		Kv cond = Kv.by("userId", userId);
		if (status != null) {
			cond.set("status", status);
		}
		SqlPara sql = Db.getSqlPara("findOrderByType", cond);
		List<Record> orderList = Db.find(sql);
		if (orderList == null) {
			renderError(404);
			return;
		}

		for (Record record : orderList) {
			Long orderId = record.getLong("id");
			String code = hashids.encode(orderId);
			record.set("orderCode", code);
			List<Record> productList = new ArrayList<>();
			Kv cond1 = Kv.by("orderId", orderId);
			SqlPara sqlPara1 = Db.getSqlPara("orderProducts", cond1);
			productList = Db.find(sqlPara1);
			record.set("productList", productList);
		}
		setAttr("status", status);
		setAttr("orderList", orderList);
		render("/res/orderList.html");
		// renderJson(orderList);
	}

	/**
	 * 订单详情
	 */
	public void orderInfo() {
		String code = getPara();
		Long orderId = hashids.decode(code)[0];
		System.out.println(orderId);
		Kv cond = Kv.by("orderId", orderId);
		SqlPara sqlPara = Db.getSqlPara("orderInfo", cond);
		List<Record> productList = null;
		Record record = Db.findFirst(sqlPara);
		if (record == null) {
			renderError(404);
			return;
		}
		if (record.getLong("productItemId") == 0 && record.getLong("groupProductId") != 0) {// 团购订单
			SqlPara sqlPara2 = Db.getSqlPara("tgOrderProductInfo", cond);
			productList = Db.find(sqlPara2);
			productList.get(0).set("size", productList.get(0).getInt("size") + "人团");
		} else {
			SqlPara sqlPara2 = Db.getSqlPara("orderProductInfo", cond);
			productList = Db.find(sqlPara2);
		}

		if (record.getStr("address") != null) {
			String[] address = record.getStr("address").split(" ");
			setAttr("name", address[0]);
			setAttr("mobile", address[1]);
			setAttr("address", address[2]);
		}
		setAttr("orderInfo", record);

		// {
		// "payType":null,
		// "address":"自己 6516516 按市场价卡就差嘎",
		// "outTradeNo":"201808150436053LYAKOek",
		// "productItemId":4,
		// "paid":0,
		// "groupProductId":0,
		// "startTime":"2018-08-15 16:36:05",
		// "id":55,
		// "shopId":null,
		// "productNum":null,
		// "status":2
		// }
System.out.println(productList.toString());
		setAttr("productList", productList);

		// [
		// {
		// "cover":"http://i.imgur.com/U3VsKfN.jpg",
		// "productId":201812,
		// "size":"小",
		// "totalFee":8888,
		// "price":8888,
		// "name":"精减套餐",
		// "productNum":1,
		// "desc":"这是一种神秘的东方力量"
		// },
		// {
		// "cover":"http://www.imagewa.com/PhotoPreview/168/168_16069.jpg",
		// "productId":201813,
		// "size":"大",
		// "totalFee":8888,
		// "price":8888,
		// "name":"养生餐",
		// "productNum":1,
		// "desc":"这是一种神秘的东方力量"
		// }
		// ]
		// renderJson(productList);
		render("/res/orderInfo.html");

	}

	/**
	 * 判断是否可以下单
	 * 
	 * @param groupId
	 * @return
	 */
	protected boolean canJoin(Long groupId) {
		TgGroup tgGroup = TgGroup.dao.findById(groupId);
		if (tgGroup.getJoinLeft() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 查询发起团购是否需要重新下单
	 * 
	 * @param groupProducId
	 * @return
	 */
	protected Ret isExistOpenOrder(Long groupProductId) {
		String extra = OrderUtils.GROUP_PRODUCT + groupProductId;
		Kv cond = Kv.by("userId", getUser().getId()).set("groupProducId", extra);
		SqlPara sql = Db.getSqlPara("findOpenOrderByStatus", cond);
		List<Record> list = Db.find(sql);
		if (list.size() == 0) {
			return Ret.fail();
		}
		Long orderId = list.get(0).getLong("id");
		if (orderId == null) {
			return Ret.fail();
		}
		return Ret.ok("orderId", orderId);
	}

	/**
	 * 查询我要参团是否需要重新下单
	 * 
	 * @param groupId
	 * @return
	 */
	protected Ret isExistJoinOrder(Long groupId) {
		String extra = OrderUtils.GROUP + groupId;
		Kv cond = Kv.by("userId", getUser().getId()).set("groupId", extra);
		SqlPara sql = Db.getSqlPara("findJoinOrderByStatus", cond);
		List<Record> list = Db.find(sql);
		if (list.size() == 0) {
			return Ret.fail();
		}
		Long orderId = list.get(0).getLong("id");
		if (orderId == null) {
			return Ret.fail();
		}
		return Ret.ok("orderId", orderId);
	}

	/**
	 * 发起团购下单
	 * 
	 * @param num
	 * @param groupProductId
	 * @return
	 */
	protected TgOrder addOpenGroupOrder(Integer num, long groupProductId) {
		TgGroupProduct groupProduct = TgGroupProduct.dao.findById(groupProductId);
		Long productId = groupProduct.getProductId();
		TgOrder order = new TgOrder();
		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				TgProduct product = TgProduct.dao.findById(productId);// 商品信息
				TgGroupProduct tgGroupProduct = TgGroupProduct.dao.findById(groupProductId);
				order.save();
				String time = DateUtils.dateFormat(new Date(), "YYYYMMddhhmmss");
				String hash = hashids.encode(order.getId());
				String outTradeNo = time + hash;

				order.setStartTime(new Date());
				order.setOutTradeNo(outTradeNo);// 订单号
				order.setFee(tgGroupProduct.getPrice());// 单价
				order.setTotalFee(tgGroupProduct.getPrice() * num);// 总价
				order.setStatus(TgOrder.STATUS_NO_PAY);// 未支付
				order.setProductNum(num);// 商品数量
				order.setUserId(getUser().getId());// 用户id
				order.setExtra("GROUP_PRODUCT:" + groupProductId);
				order.update();

				TgUserProductOrder tgUserProductOrder = new TgUserProductOrder();
				tgUserProductOrder.setOrderId(order.getId());
				tgUserProductOrder.setUserId(getUser().getId());
				tgUserProductOrder.setName(getUser().getName());
				tgUserProductOrder.setGroupProductId(groupProductId);
				tgUserProductOrder.setProductId(product.getId());
				tgUserProductOrder.setTotalFee(tgGroupProduct.getPrice());// 商品价格
				tgUserProductOrder.setProductNum(num);// 商品数量
				tgUserProductOrder.save();
				return true;
			}
		});
		return order;
	}

	/**
	 * 我要参团下单
	 * 
	 * @param num
	 * @param groupProductId
	 * @return
	 */
	protected TgOrder addJoinGroupOrder(Integer num, long groupId) {
		TgGroup tgGroup = TgGroup.dao.findById(groupId);
		tgGroup.setJoinLeft(tgGroup.getJoinLeft() - 1);
		TgOrder order = new TgOrder();
		long groupProductId = tgGroup.getGroupProductId();
		TgGroupProduct groupProduct = TgGroupProduct.dao.findById(groupProductId);
		Long productId = groupProduct.getProductId();

		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				TgProduct product = TgProduct.dao.findById(productId);// 商品信息
				order.save();
				String time = DateUtils.dateFormat(new Date(), "YYYYMMddhhmmss");
				String hash = hashids.encode(order.getId());
				String outTradeNo = time + hash;

				order.setStartTime(new Date());
				order.setOutTradeNo(outTradeNo);// 订单号
				order.setFee(groupProduct.getPrice());// 单价
				order.setTotalFee(groupProduct.getPrice() * num);// 总价
				order.setStatus(TgOrder.STATUS_NO_PAY);// 未支付
				order.setProductNum(num);// 商品数量
				order.setUserId(getUser().getId());// 用户id
				order.setExtra("GROUP:" + groupId);
				order.update();

				TgUserProductOrder tgUserProductOrder = new TgUserProductOrder();
				tgUserProductOrder.setOrderId(order.getId());
				tgUserProductOrder.setUserId(getUser().getId());
				tgUserProductOrder.setName(getUser().getName());
				tgUserProductOrder.setProductId(product.getId());
				tgUserProductOrder.setGroupProductId(groupProductId);
				tgUserProductOrder.setTotalFee(groupProduct.getPrice());// 商品价格
				tgUserProductOrder.setProductNum(num);// 商品数量
				tgUserProductOrder.save();
				return true;
			}
		});
		return order;
	}

	/**
	 * 获取当前用户的收货地址
	 * 
	 * @return
	 */
	protected List<Record> getAddressList() {
		Long userId = getUser().getId();
		Kv cond = Kv.by("userId", userId);
		SqlPara sql = Db.getSqlPara("findAddress", cond);
		List<Record> list = Db.find(sql);
		return list;
	}
}
